package com.ruoyi.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.domain.AdvIncomedetail;
import com.ruoyi.domain.AdvOrders;
import com.ruoyi.domain.Vo.AdvIncomeVo;
import com.ruoyi.domain.Vo.InComeDetailResponse;
import com.ruoyi.mapper.AdvIncomedetailMapper;
import com.ruoyi.mapper.AdvMembersMapper;
import com.ruoyi.mapper.AdvOrdersMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.mapper.AdvIncomeMapper;
import com.ruoyi.domain.AdvIncome;
import com.ruoyi.service.IAdvIncomeService;
import org.springframework.transaction.annotation.Transactional;

/**
 * bal_flagService业务层处理
 *
 * @author ruoyi
 * @date 2024-05-13
 */
@Slf4j
@Service
public class AdvIncomeServiceImpl implements IAdvIncomeService
{
    @Autowired
    private AdvIncomeMapper advIncomeMapper;
    @Autowired
    private AdvOrdersMapper advOrdersMapper;
    @Autowired
    private AdvIncomedetailMapper advIncomedetailMapper;
    @Autowired
    private AdvMembersMapper advMembersMapper;

    /**
     * 查询bal_flag
     *
     * @param advIncomeId bal_flag主键
     * @return bal_flag
     */
    @Override
    public AdvIncome selectAdvIncomeByAdvIncomeId(Long advIncomeId)
    {
        return advIncomeMapper.selectAdvIncomeByAdvIncomeId(advIncomeId);
    }

    /**
     * 查询bal_flag列表
     *
     * @param advIncome bal_flag
     * @return bal_flag
     */
    @Override
    public List<AdvIncome> selectAdvIncomeList(AdvIncome advIncome)
    {
        return advIncomeMapper.selectAdvIncomeList(advIncome);
    }

    /**
     * 新增bal_flag
     *
     * @param advIncome bal_flag
     * @return 结果
     */
    @Override
    public int insertAdvIncome(AdvIncome advIncome)
    {
        return advIncomeMapper.insertAdvIncome(advIncome);
    }

    /**
     * 修改bal_flag
     *
     * @param advIncome bal_flag
     * @return 结果
     */
    @Override
    public int updateAdvIncome(AdvIncome advIncome)
    {
        return advIncomeMapper.updateAdvIncome(advIncome);
    }

    /**
     * 批量删除bal_flag
     *
     * @param advIncomeIds 需要删除的bal_flag主键
     * @return 结果
     */
    @Override
    public int deleteAdvIncomeByAdvIncomeIds(Long[] advIncomeIds)
    {
        // 删除收益前, 需要把收益明细中相关的数据删除
        advIncomedetailMapper.deleteByAdvIncomeIds(advIncomeIds);
        return advIncomeMapper.deleteAdvIncomeByAdvIncomeIds(advIncomeIds);
    }

    /**
     * 删除bal_flag信息
     *
     * @param advIncomeId bal_flag主键
     * @return 结果
     */
    @Override
    public int deleteAdvIncomeByAdvIncomeId(Long advIncomeId)
    {
        return advIncomeMapper.deleteAdvIncomeByAdvIncomeId(advIncomeId);
    }

    /**
     * 结算生成
     * @param advIncomeVo
     * @return
     */
    @Transactional
    @Override
    public boolean settleAccount(AdvIncomeVo advIncomeVo) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
        // 1. 设置规定时间
        if (advIncomeVo.getCalMode().equals("1")) {
            // 表示为 日结
            try {
                final Date parse = simpleDateFormat.parse(advIncomeVo.getCalDate());
                parse.setHours(23);
                parse.setMinutes(59);
                parse.setSeconds(59);
                final String endDate = simpleDateFormat.format(parse);
                advIncomeVo.setCalEndDate(endDate);
            } catch (ParseException e) {
                log.error("结算生成错误{}",e);
                throw new ServiceException("日期转换错误");
            }
        }
        if (advIncomeVo.getCalMode().equals("2")) {
            // 表示是月结
            final Date startDate = new Date(Integer.valueOf(advIncomeVo.getCalYear()) - 1900,
                                       Integer.valueOf(advIncomeVo.getCalMonth()) - 1, 1);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            // 获取当前月份并加1
            int currentMonth = calendar.get(Calendar.MONTH); // 注意月份是从0开始的，即0代表1月
            calendar.add(Calendar.MONTH, 1);
            final Date endDate = calendar.getTime();
            advIncomeVo.setStartMonth(simpleDateFormat2.format(startDate));
            advIncomeVo.setEndMonth(simpleDateFormat2.format(endDate));
        }
        // 2. 根据结算类型得到所在时间内的所有未结算订单
        final List<AdvOrders> ordersByTime = advOrdersMapper.findOrderByTime(advIncomeVo);
        if (ordersByTime.size() == 0) {
            return false;
        }
        // 3. 遍历结果, 把每一个会员的 总收益计算出, 放在map中, 订单id放在一个 list 中
        Map<Long, Double> incomes = new HashMap<>(); // key 是会员id  value 是总金额
        Map<Long, List<Long>> orderIds = new HashMap<>(); // key 是会员id  value 是订单id集合
        double taxRate = advIncomeVo.getTaxRate() / 100.0; // 将 Long 类型的税率转换为 Double 类型并转换为百分数
        for (AdvOrders advOrders : ordersByTime) {
            final Long advMembersId = advOrders.getAdvMembersId();
            final Double income = incomes.get(advMembersId);
            if (income == null) {
                // 如果没有值就添加一个新键值对
                incomes.put(advMembersId, advOrders.getOrdersamount()*taxRate);
                ArrayList<Long> list = new ArrayList<>();
                list.add(advOrders.getAdvOrdersId());
                orderIds.put(advMembersId, list);
            } else {
                // 如果有值就更新值
                incomes.put(advMembersId, income + advOrders.getOrdersamount()*taxRate);
                List<Long> orders = orderIds.get(advMembersId);
                orders.add(advOrders.getAdvOrdersId());
                orderIds.put(advMembersId, orders);
            }
        }
        // 4. 把对应的信息设置到 advIncome 中, 插入会员结算收益表中
        List<AdvIncome> incomeList = new ArrayList<AdvIncome>(); // 用于保存每一条advIncome
        Set<Long> incomesKeySet = incomes.keySet();
        for (Long incomesKey : incomesKeySet) {
            AdvIncome advIncome = new AdvIncome(
                    0L,
                    advIncomeVo.getCalDate(),
                    advIncomeVo.getCalMode(),
                    advIncomeVo.getTaxRate(),
                    incomes.get(incomesKey) + "",
                    "0",
                    0.0,
                    "0",
                    incomesKey + "",
                    advIncomeVo.getCalYear(),
                    advIncomeVo.getCalMonth(),
                    "0",
                    ""
            );
            incomeList.add(advIncome);
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 5. 遍历income集合
        System.out.println("incomeList.size()--->"+incomeList.size());
        for (int i = 0; i < incomeList.size(); i++) {
            AdvIncome advIncome = incomeList.get(i);
            advIncomeMapper.insertAdvIncome(advIncome);
            // 5.1 根据advIncome的id查询到下级的id
            List<Long> nextIds = advMembersMapper.getNextIds(Long.valueOf(advIncome.getAdvMembersId()));
            System.out.println("nextIds.size()----->"+nextIds.size());
            for (Long nextId : nextIds) {
                System.out.println("下级ID-------------->"+nextId);
            }
            // 5.2 遍历从i之后的advincome, 查看是否存在下级id
            for (int j = 0; j < incomes.size(); j++) {
                System.out.println("Long.valueOf(incomeList.get(j).getAdvMembersId())"+Long.valueOf(incomeList.get(j).getAdvMembersId()));

                if (nextIds.contains(Long.valueOf(incomeList.get(j).getAdvMembersId()))) {
                    System.out.println("--------->"+advIncome.getTotalAmountSub()+"<--------->"+incomeList.get(j).getTotalAmount());
                    Double faAmount = Double.valueOf(advIncome.getTotalAmountSub());
                    Double sonAmount = Double.valueOf(incomeList.get(j).getTotalAmount());
                    Double sonTaxRate = Double.valueOf(incomeList.get(j).getTaxRate() / 100.0);
                    System.out.println("下级会员的钱: " + sonAmount);
                    System.out.println("上级会员的钱: " + faAmount);
                    System.out.println("下级会员的比例: " + sonTaxRate);
                    advIncome.setTotalAmountSub((faAmount + sonAmount + "")); // (faAmount + (sonAmount * sonTaxRate)) + ""
                }
            }
            advIncome.setPayAmount((Double.valueOf(advIncome.getTotalAmount())
                                + Double.valueOf(advIncome.getTotalAmountSub())));
            // 5.3 遍历之后, 把当前advIncome设置进入数据库
            advIncomeMapper.updateAdvIncome(advIncome);
            // 5.4 根据[会员订单id][结算收益id]插入数据到[会员结算收益明细表]
            List<Long> orderIdList = orderIds.get(Long.valueOf(advIncome.getAdvMembersId()));
            for (Long orderId : orderIdList) {
                advIncomedetailMapper.insertAdvIncomedetail(new AdvIncomedetail(
                        UUIDUtils.timeMillisId(),
                        advIncome.getAdvIncomeId(),
                        orderId
                ));
                // 5.4.1 设置结算过的订单的是否结算字段为 1[已结算]
                advOrdersMapper.updateBalFlag(orderId);
            }
        }
        return true;
    }

    @Override
    public String getIncome(Long advMembersId) {
        String amount = advIncomedetailMapper.getIncome(advMembersId);
        return amount;
    }

    /**
     * 获取收益详情
     * @param advMembersId
     * @return
     */
    @Override
    public List<InComeDetailResponse> getIncomeDetail(Long advMembersId) {
        List<InComeDetailResponse> result = advIncomedetailMapper.getIncomeDetail(advMembersId);
        return result;
    }

    @Override
    public int batchSelect(List<Long> advIncomeIds, String isAudit) {
        return advIncomeMapper.batchSelect(advIncomeIds, isAudit);
    }

    @Override
    public List<AdvIncome> selectAdvIncomeByIds(List<Long> advIncomeIds) {
        return advIncomeMapper.selectAdvIncomeByIds(advIncomeIds);
    }

}










